package com.csw.pojo;

import javax.swing.*;
import java.util.*;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author A
 * @version 1.0
 * @description: TODO
 * @date 2022/12/2 18:45
 */
public class Box {
    public static List<Brand> brandList=new ArrayList<Brand>();

    public void setBrandList(Brand brand){
        brandList.add(brand);
        //按名字排序
        brandList.sort(Comparator.comparing(Brand::getName));
        //获取牌的名称
        Map<String, List<Brand>> map = brandList.stream().collect(Collectors.groupingBy(Brand::getName));
        //拿到键集合
        Set<String> set = map.keySet();
        //增强for
        for (String s : set) {
            List<Brand> brands = map.get(s);
            if (brands.size()==3){
                //用迭代器进行删除
                delete(s);
            }
        }
        paint();
        gameOver(brand);
    }

    public void paint(){
        for (int i = 0; i < brandList.size(); i++) {
            Brand brand = brandList.get(i);
            int x=i*brand.getWidth()+10;
            brand.setBounds(x,600,50,50);
        }
    }
    //迭代器增删
    private void delete(String name){
        Iterator<Brand> iterator = brandList.iterator();
        while (iterator.hasNext()){
            Brand next = iterator.next();
            if (next.getName().equals(name)){
                //通过父容器删掉自己
                next.getParent().remove(next);
                //删除当前元素
                iterator.remove();
            }

        }
    }

    private void gameOver(Brand brand){
        if (brandList.size()>=6){
            JOptionPane.showMessageDialog(brand, "游戏失败!");
        }
    }
}
